import { GET, POST, PUT, DELETE } from '../axios.config.js'

const base = window.config.ip
const projectName = '/admin'

// 获取账户信息
export const getUserPageApi = p => GET(`${base}${projectName}/user/page`, p)

// 添加用户信息
export const postUserApi = p => POST(`${base}${projectName}/user`, p)

// 获取用户信息详情
export const getUserDetailsApi = p => GET(`${base}${projectName}/user/details/${p}`)

// 校验用户名手机号
export const getDetails = p => GET(`${base}${projectName}/user/details`, p)

// 权限单位列表
export const getDeptTreeApi = p => GET(`${base}${projectName}/dept/tree`, p)

// 编辑用户信息
export const editUserApi = p => PUT(`${base}${projectName}/user`, p)

// 删除用户信息
export const deleteUserApi = p => DELETE(`${base}${projectName}/user`, p)

// 获取角色列表
export const getRoleListApi = p => GET(`${base}${projectName}/role/list`, p)

// 用户名校验
export function validateUsername(rule, value, callback, isEdit) {
  // eslint-disable-next-line prefer-regex-literals
  const flag = new RegExp(/^([a-z\d]+?)$/).test(value)
  if (!flag) {
    callback(new Error('用户名支持小写英文、数字'))
  }

  if (isEdit) {
    return callback()
  }

  getDetails({ username: value }).then(response => {
    const result = response.data
    if (result !== null) {
      callback(new Error('用户名已经存在'))
    } else {
      callback()
    }
  })
}

// 手机号码校验
export function validatePhone(rule, value, callback, isEdit) {
  if (isEdit) {
    return callback()
  }
  getDetails({ phone: value }).then(response => {
    const result = response.data
    if (result !== null) {
      callback(new Error('手机号已经存在'))
    } else {
      callback()
    }
  })
}

// 更新登录密码
// type 改密方式 1.原密码修改 2. 通过手机验证码修改
export const updateLoginPassword = ({ oldPwd, newPwd, repeatPwd }) =>
  POST(`${base}${projectName}/uias_login/updatePassword`, {
    oldPwd,
    newPwd,
    repeatPwd,
    type: 1,
  })

// 忘记密码
export const retrieveLoginPassword = ({ telephone, smCode, password, repeatPwd }) =>
  POST(`${base}${projectName}/uias_login/updatePassword`, {
    telephone,
    smCode,
    newPwd: password,
    repeatPwd,
    type: 2,
  })

// 发送手机验证码
// check  校验账号是否存在 0不校验 1校验
export const sendSignCode = (mobile, check) =>
  POST(
    `${base}${projectName}/uias_login/sendSignCodeByAliyun`,
    {
      check,
      oneParam: mobile,
      sendType: '1',
    },
    {
      headers: {
        hideLoading: true,
      },
    }
  )
